<script lang = "ts" setup>
const value = ref('2021-10-29')
const month = ref('')
const year = ref('')
const holidays = [
  '2021-10-01',
  '2021-10-02',
  '2021-10-03',
  '2021-10-04',
  '2021-10-05',
  '2021-10-06',
  '2021-10-07',
]

const isHoliday = ({ dayjs }) => {
  return holidays.includes(dayjs.format('YYYY-MM-DD'))
}
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { onMounted,ref ,reactive} from 'vue';
    import api from '../api'
    import {
  Delete,
  Edit,
  Select
} from '@element-plus/icons-vue'
import { RefSymbol } from '@vue/reactivity';
    const tableData = ref([]);
onMounted(async ()=>{
    checkData();
    getCustomers();
})
//编辑
const editObj = ref({});
let dialogFormEdiit = ref(false);
//编辑车辆信息弹出
const openEdit =  (row)=>{
  //将数据存储到editObj上面
  editObj.value.id = row.id;
  editObj.value.customerid = row.customerid;
  editObj.value.vehicleid = row.vehicleid;
  editObj.value.startdate = row.startdate;
  editObj.value.enddate = row.enddate;
  editObj.value.realprice = row.realprice;
  editObj.value.realdeposit = row.realdeposit;
  editObj.value.status = row.status;
//打开
  dialogFormEdiit.value = true;
}
//保存修改后的数据
const saveEdit = async ()=>{
  formEditRef.value.validate(async (valid) => {
    if(valid){
      let result = await api.edit("api/order/edit" , editObj.value);
    console.log(result);
    dialogFormEdiit.value = false;
    if(result.code == 200){
      checkData();
          ElMessage({
        type: 'success',
        message: '普天同庆 修改成功！',
      })
    }else{
      ElMessage({
        type: 'info',
        message: '不好意思 更新失败~',
      })
    }

    }else{
      ElMessage({
        type: 'info',
        message: '更新失败 值不可以为空~',
      })
    }
  })
    
    
  }
//定义存储搜索数据的变量
const checkObj = ref({
  page:1,
  size:6
});
//定义搜索数据的方法
const checkData = async (val)=>{
  if(typeof val == 'number'){
    checkObj.value.page = val;
  }
      //查询数据
      console.log(checkObj.value);//检查是否传入数据
      let result = await api.get("/api/order/select" , checkObj.value);
      // result {code , data , message}   data->{list , count}
      //更新页面数据
      tableData.value = result.data.list;
      total.value = result.data.count;
}
const total = ref(90);
//删除确认框 start
const open = (data) => {
  ElMessageBox.confirm(
    '你真的要删除这个业务员信息吗？！',
    {
      confirmButtonText: '确定',
      cancelButtonText: '我后悔了',
      type: 'warning',
    }
  )
    .then( async () => {
      console.log(data);
        let result = await api.del("/api/order/del/" , data);
        if(result.code == 200){
         checkData();
          ElMessage({
        type: 'success',
        message: '错误的决定 删除成功了',
      })
    }else{
      ElMessage({
        type: 'info',
        message: '嘿嘿 删除失败',
      })
    }
        })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '正确的决定！！！',
      })
    })
}

//删除确认框  end
const addObj = ref({});
//保存新添加的订单信息 start
const addSave = async ()=>{
  formRef.value.validate(async (valid) => {
      if(valid){
        console.log("------")
        console.log(addObj.value)
        let result = await api.add("/api/order/add",addObj.value);
        let resultt = await api.edit("api/order/jiajia",addObj.value);
  if(result.code == 200){
          checkData();
          ElMessage({
        type: 'success',
        message: '添加新订单成功',
      })
    }else{
      ElMessage({
        type: 'info',
        message: '添加失败',
      })
    }
    dialogFormVisible.value = false;
    
      }else{
        dialogFormVisible.value = false;
        ElMessage({
        type: 'info',
        message: '失败 内容不能为空',
      })
      }

  })
 
    
}
const openadd = ()=>{
addObj.value = {};
  dialogFormVisible.value = true;
}
var dialogFormVisible = ref(false);
//添加新用户的操作 end

//表单验证start
const checkcustomer = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  console.log(addObj.value.customerid);
  if(reg.test(addObj.value.customerid)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const checkvehicle = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(addObj.value.vehicleid)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const checkstart = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(addObj.value.startdate)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const checkend = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(addObj.value.enddate)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const checkprice = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(addObj.value.realprice)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const checkdeposit = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(addObj.value.realdeposit)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const easyrules = {
  customerid:[{validator:checkcustomer,trigger:'blur'}],
  vehicleid:[{validator:checkvehicle,trigger:'blur'}],
  startdate:[{validator:checkstart,trigger:'blur'}],
  enddate:[{validator:checkend,trigger:'blur'}],
  realprice:[{validator:checkprice,trigger:'blur'}],
  realdeposit:[{validator:checkdeposit,trigger:'blur'}],

}
const formRef=ref({});
const formEditRef = ref({});
//表单验证end

//编辑的表单验证start
const editcustomer = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  console.log(editObj.value.customerid);
  if(reg.test(editObj.value.customerid)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const editvehicle = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(editObj.value.vehicleid)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const editstart = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(editObj.value.startdate)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const editend = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(editObj.value.enddate)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const editprice = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(editObj.value.realprice)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const editdeposit = function(rule,value,callback,){
  let reg=/^(?!^$)(?!^null$)(?!^undefined$).+$/;
  if(reg.test(editObj.value.realdeposit)){
        callback();
    }
    else{
        callback(new Error('输入不能为空'))
    }
}
const rules = {
  customerid:[{validator:editcustomer,trigger:'blur'}],
  vehicleid:[{validator:editvehicle,trigger:'blur'}],
  startdate:[{validator:editstart,trigger:'blur'}],
  enddate:[{validator:editend,trigger:'blur'}],
  realprice:[{validator:editprice,trigger:'blur'}],
  realdeposit:[{validator:editdeposit,trigger:'blur'}],
}
//编辑的表单验证end

//选择客户的下拉框实现---------------------------------------------------------start
const customerlist = ref([]);
const getCustomers = async function(){
  let result = await api.get("api/order/getcustomer");
  customerlist.value = result.data;
}

//选择客户的下拉框实现---------------------------------------------------------end

//选择车辆的下拉框------------------------------------------------------------start
//多级选择=====================================start

const cascaderProps = {
  lazy:true,
  lazyLoad(node,resolve){
    const {level,value} = node;
    if(level === 0){
      fetchBrands(resolve);
    }else if(level === 1){
      fetchModels(value,resolve);
    }else if(level === 2){
      fetchPlates(value,resolve);
    }
  },
  value:'value',
  label:'label',
  children:'children'
};
const fetchBrands = async (resolve) =>{
  try{
    const result = await api.get("api/order/getbrands");
    console.log('Brands fetched:', result.data); 
    const brands = result.data.map(brand=>({
      value:brand.id,
      label:brand.name,
      leaf:false
    }));
    resolve(brands);
  }catch(error){
    console.error("111",error);
  }
};
const fetchModels = async (brandid,resolve) =>{
  try{
    const result = await api.get(`api/order/getmodelbyid/${brandid}`,);
    console.log(result)
    console.log('Models fetched:', result.data); 
    const models = result.data.map(model=>({
      value:model.model,
      label:model.model,
      leaf:false
    }));
    resolve(models);
  }catch(error){
    console.error("222",error);
  }
};
const fetchPlates = async (modelname,resolve) =>{
  
    const result = await api.get(`api/order/getPlateNum/${modelname}`);
    console.log('Plates fetched:', result.data); 
    if(result.data &&Array.isArray(result.data)){
        const plates = result.data.map(plate=>({
          value:plate.vehicleid,
          label:plate.plateNumber,
          leaf:true
        }));
        resolve(plates);
    }else{
      throw new Error("4444");
    }
  
};
const  handleVehicleChange = function(value) {
  console.log("11111111")
  console.log(value[2])
  addObj.value.vehicleid = value[2];
}

// 级联选择器的属性定义

//多级选择===================================end
//选择车辆的下拉框------------------------------------------------------------end

//结束订单 --还车 --start
const endOrderViseable = ref(false);
const endObj = ref({});
const openEnd = function(row){

  endObj.value.customer = row.customer;
  endObj.value.startdate = row.startdate;
  endObj.value.vehicle = row.vehicle;
  endObj.value.id = row.id;
  endObj.value.enddate = row.enddate;
  endObj.value.days = row.days;
  endObj.value.totalprice;
  endObj.value.status = row.status;
  endObj.value.realprice = row.realprice;
  endObj.value.realdeposit = row.realdeposit;
  endObj.value.vehicleid = row.vehicleid;
  endObj.value.customerid = row.customerid
  //打开弹出框
  endOrderViseable.value = true;

}
const  endSave = async function(){
  // console.log("测试测试")
  // console.log(endObj.value.vehicleid);
  endOrderViseable.value = false;
  // console.log("要修改的订单ID是")
  // console.log(endObj.value.id);
  // console.log("测试日期")
  // console.log(endObj.value.enddate)
  let result = await api.get("api/order/check",endObj.value);
  console.log("测试")
  console.log(result.code)
  if(result.code == 200){
    if(endObj.value.status == '正在进行'){
    endObj.value.status = '已结束';
    const realdate = new Date(endObj.value.enddate);
    const nowdate = new Date(editObj.value.enddate);
    const timestamp1 = realdate.getTime();
    const timestamp2 = nowdate.getTime();
    const chazhi = timestamp1 - timestamp2;
    if(chazhi > 0){
      const daysDifference = chazhi / (1000 * 3600 * 24);
      const money = daysDifference * editObj.value.realprice;
      endObj.value.totalprice = editObj.value.totalprice + money;
    }
    let result2 = await api.edit("api/order/edit",endObj.value);
    checkData();
 
  }
  }else{
    ElMessage({
        type: 'info',
        message: '失败 检查和维修还没完成，请完成检查维修再结束订单',
      })
  }
  
}
//结束订单 -- 还车 --end
</script>


<template>
   <div style="display: flex; align-items: center;">
    <el-button type="info" plain @click = "checkData">搜索</el-button>
    <el-form :model="checkObj">
    <el-input v-model="checkObj.name" style="width: 240px" placeholder="请输入客户的姓名部分" />
    <el-button plain @click="openadd" type="primary" round >添加订单</el-button>
  </el-form>
</div>
    <el-table
      :data="tableData"
      style="width: 100%"
      :row-class-name="tableRowClassName"
    >
      <el-table-column fixed prop="id" label="编号" />
      <el-table-column prop="customer" label="客户" />
      <el-table-column prop="vehicle" label="车辆" />
      <el-table-column prop="startdate" label="开始日期" />
      <el-table-column prop="enddate" label="结束日期" />
      <el-table-column prop="days" label="天数" />
      <el-table-column prop="totalprice" label="总价格" />
      <el-table-column prop="status" label="订单状态" />
      <el-table-column prop="realprice" label="实际价格" />
      <el-table-column prop="realdeposit" label="押金" />
      <el-table-column fixed = "right" label="操作"width="180">
        <template #default = "scope">
        <el-button plain @click="openEdit(scope.row)" type="primary" :icon="Edit" circle />
        <el-button plain @click="open(scope.row.id)" type="danger" :icon="Delete" circle/>
        <el-button
        
        plain 
        @click="openEnd(scope.row)" 
        type="success" 
        :icon="Select" 
        v-if = "scope.row.status === '正在进行'"
        circle/>

    </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
  :page-size = "checkObj.size"
  :current-page = "checkObj.page"
   background layout="prev, pager, next" :total="total" @current-change="checkData" />
   <!--分页-->
    <!--编辑弹出框-->
    <el-dialog v-model="dialogFormEdiit" title="修改订单信息" width="500">
    <el-form 
    :model="editObj"
    :rules="rules"
    ref="formEditRef"
    >
      <el-form-item label=" 客户：" :label-width="formLabelWidth" prop = "customerid">
        <el-select v-model="editObj.customerid" placeholder="请选择客户">
        <el-option
        v-for = "cus in customerlist"
        :key="cus.id"
        :label = "cus.name"
        :value = "cus.id"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="车辆ID：" :label-width="formLabelWidth" prop = "vehicleid">
        <el-input v-model="editObj.vehicleid" autocomplete="off" />
      </el-form-item>
      <el-form-item label="开始日期：" :label-width="formLabelWidth" prop = "startdate">
        <el-date-picker
      v-model="editObj.startdate"
      type="date"
      placeholder="Pick a day"
      format="YYYY/MM/DD"
      value-format="YYYY-MM-DD"
    >
      <template #default="cell">
        <div class="cell" :class="{ current: cell.isCurrent }">
          <span class="text">{{ cell.text }}</span>
          <span v-if="isHoliday(cell)" class="holiday" />
        </div>
      </template>
    </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期：" :label-width="formLabelWidth" prop = "enddate">
        <el-date-picker
      v-model="editObj.enddate"
      type="date"
      placeholder="Pick a day"
      format="YYYY/MM/DD"
      value-format="YYYY-MM-DD"
    >
      <template #default="cell">
        <div class="cell" :class="{ current: cell.isCurrent }">
          <span class="text">{{ cell.text }}</span>
          <span v-if="isHoliday(cell)" class="holiday" />
        </div>
      </template>
    </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态：" :label-width="formLabelWidth" prop = "status">
        <el-select v-model="editObj.status" placeholder="请选择状态" autocomplete="off">
          <el-option  label = "未开始" value = "未开始"    />
          <el-option  label = "正在进行" value = "正在进行"    />
          <el-option  label = "已结束" value = "已结束"    />
        </el-select>
      </el-form-item>
      <el-form-item label="实际价格：" :label-width="formLabelWidth" prop = "realprice">
        <el-input v-model="editObj.realprice" autocomplete="off" />
      </el-form-item>
      <el-form-item label="押金：" :label-width="formLabelWidth" prop = "realdeposit">
        <el-input v-model="editObj.realdeposit" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormEdiit = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
    <!--编辑弹出框-->
 <!--添加新订单的弹出框-->
 <el-dialog v-model="dialogFormVisible" title="添加新订单" width="500">
    <el-form 
    :model="addObj"
    :rules="easyrules"
    ref="formRef"
    >
      <el-form-item label="客户：" :label-width="formLabelWidth" prop="customerid">
        <el-select v-model="addObj.customerid" placeholder="请选择客户">
        <el-option
        v-for = "cus in customerlist"
        :key="cus.id"
        :label = "cus.name"
        :value = "cus.id"
        />
      </el-select>
      </el-form-item>
       <!--多级选择-->
      <el-form-item label="车辆：" :label-width="formLabelWidth" prop="vehicleid">
        <el-cascader
            v-model="addObj.vehicleid"
            :props="cascaderProps"
            placeholder="请选择车辆"
            @change="handleVehicleChange"
            style="width: 100%;"
            
          />
  <!--多级选择-->
      </el-form-item>
      <el-form-item label="开始日期：" :label-width="formLabelWidth" prop="startdate">
        <el-date-picker
      v-model="addObj.startdate"
      type="date"
      placeholder="Pick a day"
      format="YYYY/MM/DD"
      value-format="YYYY-MM-DD"
    >
      <template #default="cell">
        <div class="cell" :class="{ current: cell.isCurrent }">
          <span class="text">{{ cell.text }}</span>
          <span v-if="isHoliday(cell)" class="holiday" />
        </div>
      </template>
    </el-date-picker>

      </el-form-item>
      <el-form-item label="结束日期：" :label-width="formLabelWidth" prop="enddate">
        <el-date-picker
      v-model="addObj.enddate"
      type="date"
      placeholder="Pick a day"
      format="YYYY/MM/DD"
      value-format="YYYY-MM-DD"
    >
      <template #default="cell">
        <div class="cell" :class="{ current: cell.isCurrent }">
          <span class="text">{{ cell.text }}</span>
          <span v-if="isHoliday(cell)" class="holiday" />
        </div>
      </template>
    </el-date-picker>
      </el-form-item>
      <el-form-item label="实际价格：" :label-width="formLabelWidth" prop="realprice">
        <el-input v-model="addObj.realprice" autocomplete="off" />
      </el-form-item>
      <el-form-item label="押金：" :label-width="formLabelWidth" prop="realdeposit">
        <el-input v-model="addObj.realdeposit" autocomplete="off" />
      </el-form-item>
      <el-form-item label="订单状态：" :label-width="formLabelWidth" prop="status">
        <el-select v-model="addObj.status" placeholder="请选择状态" autocomplete="off">
          <el-option  label = "未开始" value = "未开始"    />
          <el-option  label = "正在进行" value = "正在进行"    />
          <el-option  label = "已结束" value = "已结束"    />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addSave">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
    <!--添加新用户的弹出框-->

    <!--结束订单的弹出框-->
    <el-dialog v-model="endOrderViseable" title="结束订单" width="500">
    <el-form 
    :model="addObj"
    :rules="easyrules"
    ref="formRef"
    >
      <el-form-item label="客户：" :label-width="formLabelWidth" prop="customerid">
        <el-input v-model="endObj.customer" autocomplete="off" :disabled = "true" />
      </el-form-item>
      <el-form-item label="车辆：" :label-width="formLabelWidth" prop="vehicleid">
        <el-input v-model="endObj.vehicle" autocomplete="off" :disabled = "true" />
      </el-form-item>
      <el-form-item label="开始日期：" :label-width="formLabelWidth" prop="startdate">
        <el-input v-model="endObj.startdate" autocomplete="off" :disabled = "true" />
      </el-form-item>
      <el-form-item label="实际结束日期：" :label-width="formLabelWidth" prop="enddate">
        <el-date-picker
      v-model="endObj.enddate"
      type="date"
      placeholder="Pick a day"
      format="YYYY/MM/DD"
      value-format="YYYY-MM-DD"
    >
      <template #default="cell">
        <div class="cell" :class="{ current: cell.isCurrent }">
          <span class="text">{{ cell.text }}</span>
          <span v-if="isHoliday(cell)" class="holiday" />
        </div>
      </template>
    </el-date-picker>
      </el-form-item>
      <el-form-item label="实际价格：" :label-width="formLabelWidth" prop="realprice">
        <el-input v-model="endObj.realprice" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="endOrderViseable = false">取消</el-button>
        <el-button type="primary" @click="endSave">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </template>
  
  
  
  <style>
  .el-table {
    --el-table-border-color: transparent;
    --el-table-border: none;
    --el-table-text-color: #000000;
    --el-table-header-text-color: #0b0b0b;
    --el-table-row-hover-bg-color: transparent;
    --el-table-current-row-bg-color: transparent;
    --el-table-header-bg-color: transparent;
    --el-table-bg-color: transparent;
    --el-table-tr-bg-color: transparent;
    --el-table-expanded-cell-bg-color: transparent;
}
  .el-table .warning-row {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
  }
  .el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
  }
  demo-date-picker {
  display: flex;
  justify-content: space-between;
}

.cell {
  height: 30px;
  padding: 3px 0;
  box-sizing: border-box;
}

.cell .text {
  width: 24px;
  height: 24px;
  display: block;
  margin: 0 auto;
  line-height: 24px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 50%;
}

.cell.current .text {
  background: #626aef;
  color: #fff;
}

.cell .holiday {
  position: absolute;
  width: 6px;
  height: 6px;
  background: var(--el-color-danger);
  border-radius: 50%;
  bottom: 0px;
  left: 50%;
  transform: translateX(-50%);
}
  </style>